﻿using SHDM.Web.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace SHDM.Web.DataAccess
{
    public class OffsetQuery
    {
        public OffsetQuery(string cmdText, int offset, int limit, params object[] parameters)
        {

            var db = new SHDMEntities();
            this.Offset = offset;
            this.Limit = limit;
            if (parameters != null && parameters.Length > 0)
            {
                this.Total = db.Database.SqlQuery<int>(string.Format("SELECT COUNT(0) FROM ({0}) AS T", cmdText), parameters).FirstOrDefault();
                this.Data = db.SqlQueryDicReader(string.Format("SELECT * FROM ({0}) AS T LIMIT {1} OFFSET {2}", cmdText, limit, offset), parameters);
            }
            else
            {
                this.Total = db.Database.SqlQuery<int>(string.Format("SELECT COUNT(0) FROM ({0}) AS T", cmdText)).FirstOrDefault();
                this.Data = db.SqlQueryDicReader(string.Format("SELECT * FROM ({0}) AS T LIMIT {1} OFFSET {2}", cmdText, limit, offset));
            }
        }

        [Newtonsoft.Json.JsonProperty("data")]
        public List<DicReader> Data
        {
            get; set;
        }
        [Newtonsoft.Json.JsonProperty("limit")]
        public int Limit
        {
            get; set;
        }
        [Newtonsoft.Json.JsonProperty("offset")]
        public int Offset
        {
            get; set;
        }
        [Newtonsoft.Json.JsonProperty("total")]
        public int Total
        {
            get; private set;
        }
    }
}